import path from 'path';
import fs from 'fs';

export const storeFile = (base64, uri, storePath, callback) => {

    function getRandomFileName(len) {

        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [];

        for (let i = 0; i < len; i++) uuid[i] = chars[Math.trunc(Math.random() * 62)];

        const time = new Date().getTime();

        return `${time}_${uuid.join('')}`;

    }

    try {
        let filename = path.parse(uri);
        let dataBuffer = new Buffer.from(base64, 'base64');

        // 启用随机文件名undone
        let filepath = getRandomFileName(8) + filename.ext;

        fs.writeFile(storePath + filepath, dataBuffer, 'binary', function (err) {
            if (err) {
                console.log(err);
                callback('存储失败!');
                return;
            }
            callback(filepath);
        })
    } catch (error) {
        console.log('store file error');
        console.log(error);
    }

}